package com.huasan.www.demon.rest.resource;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Path("/api")
public class ThirdApiResource {

	private Logger logger = LoggerFactory.getLogger(ThirdApiResource.class);
	
	public static final String JSON_TEMPLATE = "{\"status\":\"{0}\",\"data\":{1}, \"userid\":\"{2}\", \"msg\":\"{3}\"}";
	
	@GET
	@Path("/oauth")
	@Produces({MediaType.APPLICATION_JSON} )
	public Response apiOauth(@QueryParam("app_id") String app_id, @QueryParam("app_secret") String app_secret,
			@QueryParam("grant_type") String grant_type, @QueryParam("redirect_uri") String redirect_uri,
			@QueryParam("code") String code){
		try{
			String url = "https://oauth.api.189.cn/emp/oauth2/v2/access_token?app_id="+app_id+"&app_secret="+app_secret+"&grant_type="+grant_type+"&redirect_uri="+redirect_uri+"&code="+code;
			HttpClient client = new DefaultHttpClient() ;
			HttpGet get = new HttpGet(url);
			HttpResponse res = client.execute(get);
			return Response.status(res.getStatusLine().getStatusCode())
					.entity(EntityUtils.toString(res.getEntity(),"UTF-8")).build();
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			return Response.status(404).entity(getErrRet("Demon get location error")).build();
		}
	}
	
	@GET
	@Path("/location")
	@Produces({MediaType.APPLICATION_JSON} )
	public Response apiLocation(@QueryParam("app_id") String app_id, @QueryParam("access_token") String access_token,
			@DefaultValue("JSON") @QueryParam("format") String format, @QueryParam("timestamp") String timestamp){
		try{
			if (timestamp==null || "".equals(timestamp)){
				Date date = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
				timestamp = sdf.format(date);
			}
			String url = "http://api.189.cn/HpInfoQuery/Enabler/location_hp?app_id="+app_id+"&access_token="+access_token+"&format="+format+"&timestamp="+timestamp;
			HttpClient client = new DefaultHttpClient() ;
			HttpGet get = new HttpGet(url);
			HttpResponse res = client.execute(get);
			return Response.status(res.getStatusLine().getStatusCode())
						.entity(EntityUtils.toString(res.getEntity(),"UTF-8")).build();
		}catch(Exception e){
			logger.error(e.getMessage(),e);
			return Response.status(404).entity(getErrRet("Demon get location error")).build();
		}
	}
	
	private String getOkRet(String sid, String uid, String msg){
		return JSON_TEMPLATE.replace("{0}", "ok").replace("1", sid)
				.replace("{2}", uid).replace("{3}", msg);
	}
	
	private String getErrRet( String msg ){
		return JSON_TEMPLATE.replace("{0}", "err").replace("1", "")
				.replace("{2}", "").replace("{3}", msg);
	}
}
